<template>
  <div>
    <TopFilter :list="insuranceFilterList" :cols="3" :rows="2" :labelWidth="90" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="insurancTable"
      :columns="insurancColumns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="multiple"
      :datakey="'rows'"
      :onRowSelectChange="SelectChange"
      :onColumnsChange="columns => (this.insurancColumns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" @click="showAdd()">新增</el-button>
        <el-button size="small" type="primary" @click="modify()">修改</el-button>
        <el-button size="small" type="primary" @click="policy()">跟踪</el-button>
        <el-button size="small" type="primary" @click="policyHis()">跟踪历史</el-button>
        <el-button size="small" type="primary">打印</el-button>
        <AjaxButton size="small" type="primary" :click="removeInsurance">退保</AjaxButton>
        <AjaxButton size="small" type="primary" :click="complete">完成</AjaxButton>
        <el-button size="small" type="primary" :loading="exportLoading" @click="insuranceExportData">导出</el-button>
      </template>
    </FilterTable>
    <!-- <Drawer
      :visible.sync="visible"
      title="分配权限"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    ></Drawer>-->
    <Drawer :visible.sync="showAddNew" title="保险投保编辑" :width="1000" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditPanel :type="type" @saveDialog="getLicense" @close="showAddNew = false" :TBcode="TBcode" :rowData="formData" />
    </Drawer>
    <BaseDialog title="投保单跟踪" :visible.sync="PolicyDialog" destroyOnClose>
      <Policy @saveDialog="getPolicy" @closeDialog="PolicyDialog = false" :TBcode="TBcode"></Policy>
    </BaseDialog>
    <BaseDialog title="投保单跟踪历史记录" :visible.sync="PolicyHisDialog" destroyOnClose>
      <PolicyHis @closeDialog="PolicyHisDialog = false" :TBcode="TBcode"></PolicyHis>
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import {
  getInsurance,
  insuranceCompany,
  getChexSelect,
  getPinpSelect,
  getCheModelSelect,
  insuranceComplete,
  insuranceRemove,
  trackPeople,
  getExcelList
} from '@/api/derived/insurance/insurancePolicy';
import EditPanel from '@/pages/derived/insurance/insurancePolicy/editPanel/editPanel';
import Policy from '@/pages/derived/insurance/insurancePolicy/editPanel/Policy';
import PolicyHis from '@/pages/derived/insurance/insurancePolicy/editPanel/PolicyHis';
//查询保险顾问
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { formatDat } from '@/utils/validate'; //时间戳转换成年月日
import AjaxButton from '@/components/AjaxButton';

export default {
  name: 'Rolemanage',
  mixins: [dictionary],
  components: {
    EditPanel,
    Policy,
    PolicyHis
  },
  data() {
    this.BaseTable = null;
    return {
      insuranceFilterList: this.createInsuranceFilterList(),
      visible: false,
      fetchApi: getInsurance,
      fetchParams: { xhrAbort: true },
      insurancColumns: this.createInsurancColumns(),
      showAddNew: false, //新增
      type: '',
      PolicyDialog: false, //跟踪
      PolicyHisDialog: false, //跟踪历史
      biandId: '', //品牌
      TBcode: '', //投保单号
      formStuas: '', //单据状态
      formData: '', //行数据
      exportLoading: false //下载
    };
  },
  methods: {
    createInsuranceFilterList() {
      return [
        {
          type: 'RANGE_DATE',
          dateType: 'exactdaterange',
          label: '保险销售日期',
          fieldName: 'insSalesDate|insSalesDateEnd',
          initialValue: [formatDat(new Date()), formatDat(new Date())]
        },
        {
          type: 'SELECT',
          label: '是否本地投保',
          fieldName: 'isLocal',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否信贷投保',
          fieldName: 'isCredit',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '保险公司名称',
          fieldName: 'insCompany',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '保险顾问',
          fieldName: 'insBroker',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '投保人姓名',
          fieldName: 'proposalName',
          placeholder: '投保人姓名...'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: 'VIN...'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '车牌号...'
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择',
          change: val => {
            this.changePinpSelect(val);
          },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          placeholder: '请选择',
          change: val => {
            this.changeChexSelect(val);
          },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择',
          change: val => {},
          itemList: []
        },
        {
          type: 'SELECT',
          label: '投保类型',
          fieldName: 'proposalType',
          placeholder: '请选择',

          itemList: this.createDictList('8086')
        },
        {
          type: 'SELECT',
          label: '投保渠道',
          fieldName: 'insChannl',
          placeholder: '请选择',
          itemList: this.createDictList('8062')
        },
        {
          type: 'SELECT',
          label: '跟踪人',
          filterable: true,
          fieldName: 'trackPeople',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '是否新增续保',
          fieldName: 'isAddProposal',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'formStatus',
          placeholder: '请选择',
          itemList: this.createDictList('8072')
        },
        {
          type: 'RANGE_DATE',
          dateType: 'exactdaterange',
          label: '完成日期',
          fieldName: 'completedDateB|completedDateE'
        }
      ];
    },
    createInsurancColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.permissionFun(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '投保单号',
          dataIndex: 'PROPOSAL_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '投保类型',
          dataIndex: 'PROPOSAL_TYPE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8086'),
          render: props => {
            return <span>{this.createDictText(props.row.PROPOSAL_TYPE, '8086')}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '品牌',
          dataIndex: 'BRAND_NAME',
          sorter: true,
          filter: true
        },
        {
          title: '车系',
          dataIndex: 'SERIES_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true
        },
        {
          title: '车型',
          dataIndex: 'MODEL_NAME',
          width: 90,
          sorter: true,
          filter: true,
          showOverflowTooltip: true
        },
        {
          title: '投保人姓名',
          dataIndex: 'PROPOSAL_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '电话',
          dataIndex: 'PHONE',
          width: 120,
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '手机',
          dataIndex: 'MOBILE',
          width: 120,
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '邮编',
          dataIndex: 'ZIP_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '地址',
          dataIndex: 'ADDRESS',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // align:"center"
        },
        {
          title: '保险顾问',
          dataIndex: 'INS_BROKER',
          sorter: true,
          filter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '保险公司名称',
          dataIndex: 'INSURATION_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true

          // align:"center"
        },
        {
          title: '交强险应收金额',
          dataIndex: 'RECEIVABLE_COM_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.RECEIVABLE_COM_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '商业险应收金额',
          dataIndex: 'RECEIVABLE_BUSI_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.RECEIVABLE_BUSI_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '车船税',
          dataIndex: 'TRAVEL_TAX_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.TRAVEL_TAX_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '其他业务',
          dataIndex: 'OTHER_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.OTHER_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '金额合计',
          dataIndex: 'TOTAL_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.TOTAL_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '是否本地投保',
          dataIndex: 'IS_INS_LOCAL',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.IS_INS_LOCAL, '1004')}</span>;
          }
        },
        {
          title: '是否信贷投保',
          dataIndex: 'IS_INS_CREDIT',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.IS_INS_CREDIT, '1004')}</span>;
          }
        },
        {
          title: '投保渠道',
          dataIndex: 'INS_CHANNELS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8062'),
          render: props => {
            return <span>{this.createDictText(props.row.INS_CHANNELS, '8062')}</span>;
          }
        },
        {
          title: '跟踪人',
          dataIndex: 'TRANCER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '完成日期',
          dataIndex: 'COMPLETED_DATE',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '跟进状态',
          dataIndex: 'TRACE_TYPE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8058'),
          render: props => {
            return <span>{this.createDictText(props.row.TRACE_TYPE, '8058')}</span>;
          }
        },
        {
          title: '单据状态',
          dataIndex: 'FORM_STATUS',
          sorter: true,
          filter: true,
          // filterType: 'checkbox',
          filterItems: this.createDictList('8072'),
          render: props => {
            return <span>{this.createDictText(props.row.FORM_STATUS, '8072')}</span>;
          }
        },
        // {
        //   title: '是否已过户',
        //   dataIndex: 'IS_TRANSFER',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.IS_TRANSFER, '1004')}</span>;
        //   }
        // },
        {
          title: '保险销售日期',
          dataIndex: 'INS_SALES_DATE',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd',
          filterType: 'date-range'
        },
        {
          title: '交强险保单号',
          dataIndex: 'COM_INS_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // align:"center"
        },
        {
          title: '商业险保单号',
          dataIndex: 'BUSI_INS_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // align:"center"
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // align:"center"
        },
        {
          title: '是否新增续保',
          dataIndex: 'IS_ADD_PROPOSAL',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.IS_ADD_PROPOSAL, '1004')}</span>;
          }
        },
        {
          title: '是否本公司投保',
          dataIndex: 'IS_SELF_COMPANY_INSURANCE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.IS_SELF_COMPANY_INSURANCE, '1004')}</span>;
          }
        }
      ];
    },
    // 选中行
    SelectChange(row) {
      console.log('row', row);
      let TBcode = row[0].PROPOSAL_CODE;
      let formStuas = row[0].FORM_STATUS;
      this.TBcode = String(TBcode);
      this.formStuas = String(formStuas);
      this.formData = row[0];
    },
    //新增
    showAdd() {
      this.type = 'add';
      this.showAddNew = true;
    },
    //修改
    modify() {
      if (this.formStuas == '80721002' || this.formStuas == '80721003' || this.formStuas == '80721005') {
        this.$notify.warning({ title: '提示信息', message: '单据状态为已成交、已完成和已结案的单据不能修改！' });
        return;
      } else {
        if (!this.TBcode) {
          this.$notify.warning({ title: '提示信息', message: '请选择表格数据' });
          return;
        }
      }
      this.type = 'modify';
      this.showAddNew = true;
    },
    changeHandle(val) {
      console.log('val', val);
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    getLicense(val) {
      console.log(val, '收到的状态值');
      this.showAddNew = val.stutas;
      if (val.result === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    getPolicy(type) {
      this.PolicyDialog = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    //跟踪
    policy() {
      if (this.formStuas == 80721002 || this.formStuas == 80721003 || this.formStuas == 80721005) {
        this.$notify.warning({ title: '提示信息', message: '单据状态为已成交、已完成和已结案的单据不能修改！' });
        return;
      } else {
        if (!this.TBcode) {
          this.$notify.warning({ title: '提示信息', message: '请选择表格数据' });
          return;
        }
      }
      this.PolicyDialog = true;
    },
    //跟踪历史
    policyHis() {
      if (!this.TBcode) {
        this.$notify.warning({ title: '提示信息', message: '请选择表格数据' });
        return;
      }
      this.PolicyHisDialog = true;
    },
    //完成
    async complete() {
      console.log(this.formStuas);
      if (!this.TBcode) {
        this.$notify.warning({ title: '提示信息', message: '请选择表格数据' });
        return;
      }
      if (this.formStuas == 80721004 || this.formStuas == 80721004) {
        this.$notify.warning({ title: '提示信息', message: '单据状态为已作废、已结案的单据不可完成！' });
        return;
      } else if (this.formStuas == 80721003) {
        this.$notify.warning({ title: '提示信息', message: '单号为' + this.TBcode + '的投保单已经是完成状态' });
        return;
      } else {
        let res = await insuranceComplete(this.TBcode);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '单号为' + this.TBcode + '的投保单保存完成' });
          //刷新数据显示状态
          this.fetchParams = { ...this.fetchParams };
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg });
        }
      }
    },
    async removeInsurance() {
      if (!this.TBcode) {
        this.$notify.warning({ title: '提示信息', message: '请选择表格数据' });
        return;
      }
      if (this.formStuas == 80721002 || this.formStuas == 80721003) {
        let res = await insuranceRemove(this.TBcode);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '单号为' + this.TBcode + '的投保单已退保' });
          //刷新数据显示状态
          this.fetchParams = { ...this.fetchParams };
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg });
        }
      } else {
        this.$notify.warning({ title: '提示信息', message: '单据状态只有已完成和已成交的才能退保！' });
        return;
      }
    },

    //明细
    permissionFun(roleId) {
      this.type = 'permission';
      this.showAddNew = true;
      this.TBcode = String(roleId.PROPOSAL_CODE);
      this.formData = roleId;
      console.log(this.TBcode);
    },
    // 品牌下拉框改变时
    changePinpSelect(id) {
      this.clearFormItem(this.insuranceFilterList.find(item => item.fieldName === 'series'));
      this.clearFormItem(this.insuranceFilterList.find(item => item.fieldName === 'model'));
      if (!id) return;
      this.getChexSelect(id);
      this.biandId = id;
    },
    // 车系下拉框改变时
    changeChexSelect(id) {
      this.clearFormItem(this.insuranceFilterList.find(item => item.fieldName === 'model'));

      if (!id) return;

      this.getCheModelSelect(this.biandId, id);
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    //保险公司
    async insuranceCompany() {
      const res = await insuranceCompany();
      console.log('保险公司', res);
      this.insuranceFilterList.find(item => item.fieldName === 'insCompany').itemList = res.data.map(x => ({ value: x.INSURATION_CODE, text: x.INSURATION_NAME }));
    },
    // 保险顾问
    async insuranceService() {
      let roleParam = { role: dictCode.INSURANCE_SPECIALIST };
      const res = await searchRoleByCode(roleParam);
      console.log('保险顾问', res);
      this.insuranceFilterList.find(item => item.fieldName === 'insBroker').itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
      this.insurancColumns.find(x => x.dataIndex === 'INS_BROKER').editItems = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    //跟踪人
    async trackPeople() {
      const res = await trackPeople();
      console.log('跟踪人', res);
      this.insuranceFilterList.find(item => item.fieldName === 'trackPeople').itemList = res.data.map(x => ({ value: x.TRANCER, text: x.TRANCER_NAME }));
    },
    async getPinpSelect() {
      const res = await getPinpSelect();

      this.insuranceFilterList.find(item => item.fieldName === 'brand').itemList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
    },
    async getChexSelect(id) {
      const res = await getChexSelect(id);
      this.insuranceFilterList.find(item => item.fieldName === 'series').itemList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
    },
    async getCheModelSelect(bId, id) {
      const res = await getCheModelSelect(bId, id);
      this.insuranceFilterList.find(item => item.fieldName === 'model').itemList = res.data.map(x => ({ value: x.modelId, text: x.modelName }));
    },
    //投保单导出
    insuranceExportData() {
      this.exportLoading = true;
      getExcelList(this.fetchParams).then(res => {
        exportExcelFile(res.data, '投保单数据');
        this.exportLoading = false;
      });
    }
  },
  mounted() {
    this.BaseTable = this.$refs.insurancTable.$refs.pageTable;
    this.insuranceCompany();
    this.insuranceService();
    this.getPinpSelect();
    this.trackPeople();
  },
  created() {}
};
</script>

<style lang="less" scoped>
.box {
  border: 1px solid #ccc;
  padding-top: 15px;
  padding-right: 15px;
  border-radius: @borderRadius;
  margin-bottom: 20px;
  box-shadow: @boxShadow;
}
</style>
